import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Test from '../views/Test.vue'
import Course from '../views/Course.vue'
import Ht from '../views/Ht.vue'
import Cs from '../views/Cs.vue'
import Desc from '../views/Desc.vue'
import Login from '../views/Login.vue'
Vue.use(VueRouter)

const routes = [{
    path: '/login',
    name: 'login',
    component: Login
  }, {
    path: '/home',
    name: 'Home',
    component: HomeView,
    meta: {
      title: 'Home'
    }
  },
  {
    path: '/course',
    component: Course,
    beforeEnter: (to, from, next) => {
      console.log("路由独享守卫")
      next()
    },
    meta: {
      title: '课程中心'
    },
    children: [{
      path: '/html',
      component: Ht,
      meta: {
        title: 'html'
      }
    }, {
      name: 'css',
      path: '/css',
      component: Cs,
      meta: {
        title: 'css'
      }
    }, {
      name: 'desc',
      path: '/desc',
      component: Desc,
      props($route) {
        return {
          name: $route.query.name,
          id: $route.query.id
        }
      }
    }]
  }
]

const router = new VueRouter({
  routes,
  mode: 'history' //历史模式
})

//全局前置守卫
router.beforeEach((to, from, next) => {
  let apiKey = localStorage.getItem("apikey")
  //鉴权
  if (to.name !== 'login' && apiKey != '123') next({
    name: 'login'
  })
  else next()
})
//全局后置守卫
router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
